package pe.com.market.emarket.action;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pe.com.market.common.util.Utilitario;
import pe.com.market.emarket.model.Product;

public class EditProductAction {
	private int id;
	private String message;
	private Product product;
	
	public String edit(){
		EntityManager em=Utilitario.getInstance().getEntityManager();
		product =em.find(Product.class, id);
		return "success";
	}

	public String update(){
		EntityManager em=Utilitario.getInstance().getEntityManager();
		EntityTransaction tx=em.getTransaction();
		String camino="success";
		try{
			tx.begin();
			Product productupd =em.find(Product.class, product.getId());
			if(product.getPrice()<2.0){
				message = "The price must no to be less than $2";
				return "unsuccessful";
			}
			productupd.setName(product.getName());
			productupd.setPrice(product.getPrice());
			productupd.setExpiredDate(product.getExpiredDate());
			productupd.setCategory(product.getCategory());
			productupd.setStatus(product.getStatus());
			em.merge(productupd);
			tx.commit();
			message="The product was edited successfully";
		}catch(Exception ex){
			ex.printStackTrace();
			message="Unsuccessful Update";
			camino="error";
			tx.rollback();
		}
		return camino;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

}